using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace TowerDefence
{
    public class Bullet : MonoBehaviour
    {
        private Enemy mTarget;
        
        private float mMoveSpeed;

        private int mAttack;

        private Vector3 mTargetPos;

        private float Rang;

        private float TotalTime;

        private void Update()
        {
            if (mTarget == null)
            {
                if (mMoveSpeed > 0)
                {
                    Rang=Vector3.Distance(transform.localPosition,mTargetPos);
                    TotalTime = Rang / mMoveSpeed;
                }
                else
                {
                    TotalTime = 0;
                }
               
                if (Time.deltaTime >= TotalTime)
                {
                    
                    gameObject.SetActive(false);
                }
                else
                {
                    transform.localPosition=Vector3.Lerp(transform.localPosition,mTargetPos,Time.deltaTime  / TotalTime);
                }
            }
            else
            {
                mTargetPos= mTarget.transform.localPosition;
                if (mMoveSpeed > 0)
                {
                    Rang=Vector3.Distance(transform.localPosition,mTargetPos);
                    TotalTime= Rang / mMoveSpeed;
                }
                else
                {
                    TotalTime = 0;
                }
                
                if (Time.deltaTime >= TotalTime)
                {
                    AudioManager.PlaySound("hit");
                    mTarget.AddHP(-mAttack);
                
                    gameObject.SetActive(false);
                }
                else
                {
                    transform.localPosition=Vector3.Lerp(transform.localPosition,mTargetPos,Time.deltaTime  / TotalTime);
                }
            }
            
            
        }

        public void InitData(Enemy enemy, float moveSpeed, int atk)
        {
            mTarget = enemy;
            mMoveSpeed=moveSpeed;
            mAttack = atk;
            mTargetPos=enemy.transform.localPosition;
        }
        public void InitData( Vector3 pos, float moveSpeed, int atk)
        {
            mTarget = null;
            mMoveSpeed=moveSpeed;
            mAttack = atk;
            mTargetPos=pos;
        }
        
        
    }

}
